package com.kevin.Code.Hash;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author Vinlee Xiao
 * @Classname Leetcode_438
 * @Description Leetcode 438. 找到字符串中所有字母异位词 中等难度 hot 100
 * @Date 2021/11/29 16:43
 * @Version 1.0
 */
public class Leetcode_438 {

    List<Integer> result = new ArrayList<>();

    /**
     * 难点在于判断重复的字符
     *
     * @param s
     * @param p
     * @return
     */
    public List<Integer> findAnagrams(String s, String p) {

        int sLength = s.length();
        int pLength = p.length();

        char[] pArray = p.toCharArray();
        Arrays.sort(pArray);
        String obj = new String(pArray);

        int left = 0;

        while (left < sLength) {


            //剩余长度不够组成一个p串的异位字符串时 直接返回
            if (left + pLength > sLength) {
                break;
            }
            String sub = s.substring(left, left + pLength);
            char[] chars = sub.toCharArray();
            Arrays.sort(chars);
            String checkString = new String(chars);
            if (obj.equals(checkString)) {
                result.add(left);
            }
            left++;

        }

        return result;
    }

    /**
     * 官方题解滑动窗口：用数组统计字符的个数
     *
     * @param s
     * @param p
     * @return
     */
    public List<Integer> findAnagrams1(String s, String p) {

        int sLength = s.length();
        int pLength = p.length();

        int[] sCount = new int[26];
        int[] pCount = new int[26];

        for (int i = 0; i < pLength; i++) {
            sCount[s.charAt(i) - 'a']++;
            pCount[p.charAt(i) - 'a']++;
        }

        if (Arrays.equals(sCount, pCount)) {
            result.add(0);
        }

        //滑动窗口
        for (int i = 0; i < sLength - pLength; i++) {
            //减去前一轮字符累计的字符数量
            sCount[s.charAt(i) - 'a']--;
            //前p个已经验证过
            sCount[s.charAt(i + pLength) - 'a']++;
            if (Arrays.equals(sCount, pCount)) {
                result.add(i + 1);
            }
        }

        return result;
    }


    public static void main(String[] args) {
        Leetcode_438 leetcode_438 = new Leetcode_438();
        List<Integer> list = leetcode_438.findAnagrams1("cbaebabacd", "abc");
        for (Integer e : list) {
            System.out.println(e);
        }
    }

}
